import axios from "axios";
import qs from "qs";
import { getToken } from "xqjr-module-auth";
import { message } from "ant-design-vue";
export function publicDownLoad(file) {
  axios({
    url: "/file/api/v1/general/download",
    params: {
      filePath: file,
      downloadType: "attachment"
    },
    paramsSerializer: (param) => {
      return qs.stringify(param, { indices: false });
    },
    method: "get",
    responseType: "blob",
    headers: {
      token: getToken()
    }
  })
    .then((res) => {
      if (res.data && res.data.type === "application/json") {
        const reader = new FileReader();
        reader.readAsText(res.data, "utf-8");
        reader.onload = () => {
          const resJson = JSON.parse(reader.result);
          message.error(resJson.msg);
        };
      } else {
        const rspHeaders = res.headers;
        const blob = new Blob([res.data], { type: "application/octet-stream" });
        const link = document.createElement("a");
        try {
          const fileName = decodeURI(rspHeaders["content-disposition"].split(";")[1].split("=")[1].replaceAll('"', ""));
          link.download = fileName;
        } catch (err) {
          console.log(err);
        }
        link.href = URL.createObjectURL(blob);
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      }
    })
    .catch((err) => {
      console.log("debug log --> ", err);
    });
}
